from flask import Flask, request, jsonify, render_template
import requests

app = Flask(__name__)

@app.route('/fetch_video_comments', methods=['POST'])
def fetch_video_comments():
    data = request.get_json()
    aweme_id = data.get("aweme_id")
    count = data.get("count", 1)
    token = data.get("token")

    if not aweme_id:
        return jsonify({"error": "Missing aweme_id"}), 400

    if not token:
        return jsonify({"error": "Missing token"}), 400

    url = "https://api.tikhub.io/api/v1/douyin/app/v3/fetch_video_comments"
    headers = {
        "Authorization": f"Bearer {token}"
    }

    comments = []
    cursor = 0

    for _ in range(count):
        params = {
            "aweme_id": aweme_id,
            "cursor": cursor
        }
        try:
            response = requests.get(url, headers=headers, params=params)
            response.raise_for_status()
        except requests.RequestException as e:
            app.logger.error("Failed to fetch comments: %s", e)
            return jsonify({"error": "Failed to fetch comments"}), 500

        data = response.json()
        _comments = data.get('data', {}).get("comments", [])
        if not _comments:
            break
        comments.extend(_comments)
        cursor = data.get('data', {}).get("cursor", 0)

    return jsonify({"comments": comments})

@app.route('/', methods=['GET'])
def hello_world():
    name = request.args.get('name', 'World')
    response = {
        'code': 200,
        'msg': f'Hello, {name}!'
    }
    return jsonify(response)

@app.route('/api/v1/xiaohongshu/web/get_note_info_v4', methods=['POST'])
def get_note_info_v4():
    data = request.get_json()
    if data is None:
        app.logger.error("Failed to parse JSON data. Request data: %s", request.data)
        return "Invalid JSON data", 400

    note_id = data.get('note_id')
    token = data.get('token')

    if not note_id or not token:
        return jsonify({"error": "Missing note_id or token"}), 400

    api_url = "https://api.tikhub.io/api/v1/xiaohongshu/web/get_note_info_v4"
    headers = {
        "Authorization": f"Bearer {token}"
    }
    params = {
        "note_id": note_id
    }

    try:
        response = requests.get(api_url, headers=headers, params=params)
        response.raise_for_status()
    except requests.RequestException as e:
        app.logger.error("Failed to fetch note info: %s", e)
        return jsonify({"error": "Failed to fetch note info"}), 500

    res = response.json()
    app.logger.error("Response Data: %s", res)

    if 'detail' in res:
        code = res['detail'].get('code')
        message = res['detail'].get('message')
        return jsonify({
            'code': code,
            'data': message
        })

    notes = res.get('data', {}).get('data', [])
    return jsonify({
        'code': 0,
        'data': notes
    })

# 获取飞书应用的 access_token
@app.route('/get_tenant_access_token', methods=['POST'])
def get_tenant_access_token():
    data = request.get_json()
    if data is None:
        app.logger.error("Failed to parse JSON data. Request data: %s", request.data)
        return "Invalid JSON data", 400

    app_id = data.get('app_id')
    app_secret = data.get('app_secret')

    if not app_id or not app_secret:
        return jsonify({"error": "Missing Params"}), 400

    api_url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    headers = {
        "Content-Type": "application/json; charset=utf-8"
    }
    body = {
        "app_id": app_id,
        "app_secret": app_secret
    }
    try:
        response = requests.post(api_url, headers=headers, json=body)
        response.raise_for_status()
    except requests.RequestException as e:
        app.logger.error("Failed to fetch tenant access token: %s", e)
        return jsonify({"error": "Failed to fetch tenant access token"}), 500

    res = response.json()
    return jsonify(res)

@app.route('/chatbox', methods=['GET'])
def chatbox():
    return render_template('chatbox.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
